#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# This program is free software; you can redistribute it and/or modify  
# it under the terms of the GNU General Public License as published by  
# the Free Software Foundation; either version 2 of the License, or     
# (at your option) any later version.                                   
#                                                                         
# A copy of the license can be found in the license.txt file supplied   
# with this software or at: http://www.gnu.org/copyleft/gpl.html       
#


import os,os.path,time

import ConfigParser as configparser


try :
    from hashlib import md5 as MD5
except :
    from md5 import md5 as MD5

from consts import CELL_CONFIG_FILE

CELL_FILE_MODE = 0644
CELL_DIR_MODE  = 0755


#######################################################################

import base64
import celtuce.yaml as yaml

yaml_encode = yaml.dump
yaml_decode = yaml.load


def serialize( obj ) : 
    return base64.b64encode( yaml_encode( obj ) ) 
    ## encodeMeta()

def unserialize( obj ) : 
    return yaml_decode( base64.b64decode( obj ) ) 
    ## decodeMeta()

#######################################################################


def makeCellPath(root_path, table, key_begin, key_end) :
    if isinstance(key_end, unicode) :
        cell_dir_name = MD5(key_end.encode('utf-8')).hexdigest()[:16]
    else :
        cell_dir_name = MD5(key_end).hexdigest()[:16]
    return os.sep.join((root_path, table, cell_dir_name))
    ## makeCellpath()

def makeCellConfigFileName(cell_path) :
    return os.sep.join((cell_path, CELL_CONFIG_FILE))
    ## makeCellConfigFileName()

def saveCellConfig(filepath,table,key_begin,key_end) :
    if os.path.isdir(filepath) :
        filename = makeCellConfigFileName( filepath )
    else :
        filename = filepath

    fp = file(filename, 'w')

    fp.write("[cell]\n")

    fp.write('table:')
    fp.write(table)
    fp.write("\n")

    fp.write('key_begin:')
    fp.write(repr(key_begin))
    fp.write("\n")

    fp.write('key_end:')
    fp.write(repr(key_end))
    fp.write("\n")

    fp.write('mark:')
    fp.write( serialize( (table, key_begin, key_end) ) )
    fp.write("\n")

    fp.write("\n")
    fp.close()
    ## saveCellConfig()


def loadCellConfig(filepath) :
    if os.path.isdir(filepath) :
        filename = makeCellConfigFileName( filepath )
    else :
        filename = filepath

    ini = configparser.ConfigParser()
    ini.optionxform = lambda x: x
    ini.read(filename)

    SECTION = 'cell'
    if not ini.has_section(SECTION) :
        raise RuntimeError, 'Section [%s] does NOT exist in %s' % (SECTION, filename)

    #OPTION = 'table'
    #table_name = ini.get(SECTION, OPTION)

    #OPTION = 'key_begin'
    #key_begin = ini.get(SECTION, OPTION)

    #OPTION = 'key_end'
    #key_end = ini.get(SECTION, OPTION)

    OPTION = 'mark'
    mark = ini.get(SECTION, OPTION)

    table_name,key_begin,key_end = unserialize( mark )

    return (table_name,key_begin,key_end)
    ## loadCellConfig()




